package ru.bytedog.oiot.counter.bot.controller.rest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import ru.bytedog.oiot.counter.bot.bean.AppAuthority;
import ru.bytedog.oiot.counter.bot.bean.ErrorCode;
import ru.bytedog.oiot.counter.bot.dto.dashboard.CurrentUser;
import ru.bytedog.oiot.counter.bot.dto.dashboard.UserChangeRoleRequest;
import ru.bytedog.oiot.counter.bot.entity.BotUser;
import ru.bytedog.oiot.counter.bot.exception.ServiceException;
import ru.bytedog.oiot.counter.bot.service.UserService;

@RestController
@RequestMapping("/api/user")
public class UserController {

    private final UserService service;

    public UserController(UserService service) {
        this.service = service;
    }


    @GetMapping
    public CurrentUser setUserRole(Authentication authentication) {
        BotUser user = (BotUser) authentication.getPrincipal();
        return new CurrentUser(user.getFirstName(), user.getLastName(), user.getUsername());
    }

    @PutMapping
    public ResponseEntity<Void> setUserRole(@RequestBody UserChangeRoleRequest request) throws ServiceException {
        if (request == null || StringUtils.isBlank(request.getUsername())) {
            throw new ServiceException(ErrorCode.BAD_REQUEST);
        }
        service.changeRole(request.getUsername(), request.isAdditional() ? AppAuthority.ADMIN : AppAuthority.USER);
        return ResponseEntity.noContent().build();
    }

}
